<template>
	<view class="container">

		<!-- 头像选择区域 -->
		<view class="avatar-section">
			<view class="avatar-wrapper" @click="chooseAvatar">
				<image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
			</view>
			<text class="avatar-tip">点击更换头像</text>
		</view>

		<!-- 基本信息表单 -->
		<view class="form-section">
			<view class="form-item">
				<text class="form-label">用户名</text>
				<input class="form-input" v-model="userInfo.username" placeholder="请输入用户名" />
			</view>

			<view class="form-item">
				<text class="form-label">性别</text>
				<input class="form-input" v-model="userInfo.sex" placeholder="请输入性别" />
			</view>

			<view class="form-item">
				<text class="form-label">生日</text>
				<picker class="form-picker" mode="date" :value="userInfo.birthday" @change="onBirthdayChange"
					start="1950-01-01" end="2023-12-31">
					<view class="picker-value">{{ userInfo.birthday || '请选择' }}</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="form-label">手机号</text>
				<input class="form-input" v-model="userInfo.phone" placeholder="请输入手机号" type="number" maxlength="11" />
			</view>

			<view class="form-item form-item-textarea">
				<text class="form-label">个人简介</text>
				<textarea class="form-textarea" v-model="userInfo.introduction" placeholder="请输入个人简介" />
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="btn-section">
			<button class="submit-btn" @click="saveUserInfo">保存</button>
		</view>
		<view class="danger-zone">
			<button class="logout-btn" @click="logout">退出登录</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				globaApi: '',
				userInfo: {
					avatar: '',
					username: '',
					sex: '', // 现在改为字符串输入
					birthday: '',
					phone: '',
					introduction: '',
				},
				token: '',
				userType: 0
			}
		},
		onPullDownRefresh() {
			this.loadUserInfo();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onLoad() {
			// 加载用户信息
			this.token = uni.getStorageSync('token');
			this.globaApi = getApp().globalData.baseUrl;
			this.loadUserInfo();
		},
		onBackPress() {
			this.loadUserInfo();
		},
		methods: {
			logout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						uni.request({
							url: `${this.globaApi}/auth/logout`,
							method: 'POST',
							header: {
								'Content-Type': 'application/x-www-form-urlencoded',
								'token': this.token
							},
							data: this.userInfo,
							success: (res) => {
								if (res.data.code === 200) {
									uni.showToast({
										title: '退出登录成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: res.data.message || '保存失败',
										icon: 'none'
									});
								}
							},
							fail: () => {
								uni.showToast({
									title: '网络错误',
									icon: 'none'
								});
							}
						});
						if (res.confirm) {
							// 清除登录状态
							uni.removeStorageSync('token');
							// 返回登录页
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}
					}
				});
			},
			// 加载用户信息
			loadUserInfo() {
				const userId = uni.getStorageSync('userId');
				this.userType = uni.getStorageSync('userType');
				if (this.userType === 0) {
					var endpoint = `${this.globaApi}/userInfo/getUserInfoByUserId`;
					uni.setStorageSync('userType', 0);
				} else {
					var endpoint = `${this.globaApi}/doctor/getDoctorById`;
					uni.setStorageSync('userType', 1);
				}
				uni.request({
					url: endpoint,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						userId: userId
					},
					success: (res) => {
						if (res.data.code === 200) {
							console.log(res)
							// 将用户信息存储在本地存储中
							uni.setStorageSync('username', res.data.data.name);
							uni.setStorageSync('avatar', res.data.data.avatar);
							uni.setStorageSync('sex', res.data.data.sex);
							uni.setStorageSync('birthday', res.data.data.birthday);
							uni.setStorageSync('introduction', res.data
								.data.introduction);
							uni.setStorageSync('telephone', res.data
								.data.phone);
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '查询信息错误，请稍后重试',
							icon: 'none'
						});
					}

				})
				const cachedUserName = uni.getStorageSync('username');
				const cachedUserIntroduction = uni.getStorageSync('introduction');
				const cachedUserAvatar = uni.getStorageSync('avatar');
				const cachedUserSex = uni.getStorageSync('sex');
				const cachedUserBirthday = uni.getStorageSync('birthday');
				const cachedUserTelephone = uni.getStorageSync('telephone');
				if (cachedUserName) {
					try {
						this.userInfo.username = cachedUserName
						this.userInfo.avatar = cachedUserAvatar
						this.userInfo.sex = cachedUserSex
						this.userInfo.birthday = cachedUserBirthday
						this.userInfo.phone = cachedUserTelephone
						this.userInfo.introduction = cachedUserIntroduction
					} catch (e) {
						console.error('解析用户信息失败', e);
					}
				}
			},

			// 选择头像
			chooseAvatar() {
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['compressed'], // 压缩图片
					sourceType: ['album', 'camera'], // 从相册选择或拍照
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						// 此处可以上传图片到服务器，获取URL后再更新头像
						// 模拟场景直接使用临时路径
						this.userInfo.avatar = tempFilePaths[0];
						console.log(this.userInfo.avatar);
						// 实际项目中的上传逻辑示例
						uni.uploadFile({
							url: `${this.globaApi}/file/upload`,
							filePath: tempFilePaths[0],
							name: 'files',
							success: (uploadRes) => {
								const data = JSON.parse(uploadRes.data);
								if (data.code === 200) {
									this.userInfo.avatar = data.data;
									uni.request({
										url: `${this.globaApi}/userInfo/updateUserInfoByUserId`,
										method: 'POST',
										header: {
											'Content-Type': 'application/x-www-form-urlencoded',
											'token': this.token
										},
										data: data.data,
										success: (res) => {

										},
										fail: () => {
											uni.hideLoading();
											uni.showToast({
												title: '修改头像，请稍后重试',
												icon: 'none'
											});
										}
									})
								}
							}
						});

					}
				});
			},

			// 生日选择变化
			onBirthdayChange(e) {
				this.userInfo.birthday = e.detail.value;
			},

			// 保存用户信息
			saveUserInfo() {
				// 表单验证
				if (!this.userInfo.username.trim()) {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					});
					return;
				}

				// 手机号格式验证
				if (this.userInfo.phone && !/^1\d{10}$/.test(this.userInfo.phone)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					});
					return;
				}

				// 保存用户信息
				uni.request({
					url: `${this.globaApi}/userInfo/updateUserInfoByUserId`,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'token': this.token
					},
					data: this.userInfo,
					success: (res) => {
						if (res.data.code === 200) {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: res.data.message || '保存失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					}
				});

			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		padding: 30rpx;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.page-header {
		margin-bottom: 40rpx;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	/* 头像部分样式 */
	.avatar-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.avatar-wrapper {
		position: relative;
		width: 150rpx;
		height: 150rpx;
		border-radius: 75rpx;
		overflow: hidden;
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-edit-icon {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50rpx;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.edit-icon {
		color: #fff;
		font-size: 32rpx;
	}

	.avatar-tip {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	/* 表单部分样式 */
	.form-section {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 40rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.form-item-textarea {
		align-items: flex-start;
		padding-bottom: 30rpx;
	}

	.form-label {
		width: 160rpx;
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.form-input {
		flex: 1;
		height: 60rpx;
		font-size: 28rpx;
		color: #333;
	}

	.form-picker {
		flex: 1;
	}

	.picker-value {
		font-size: 28rpx;
		color: #333;
	}

	.form-textarea {
		flex: 1;
		height: 180rpx;
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
	}

	/* 按钮部分样式 */
	.btn-section {
		margin-top: 20rpx;
	}

	.submit-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background: linear-gradient(to right, #3399ff, #66aaff);
		color: #fff;
		font-size: 32rpx;
		border-radius: 45rpx;
	}

	.danger-zone {
		margin-top: 60rpx;
	}

	.logout-btn {
		width: 100%;
		height: 90rpx;
		background-color: #fff;
		color: #333;
		border-radius: 45rpx;
		font-size: 30rpx;
		margin-bottom: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>